#include <iostream>
#include <memory>
using namespace std;

#include <unistd.h>
#include <pthread.h>
// 使用互斥锁实现读写锁,读者优先
pthread_mutex_t r_count_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t wlock = PTHREAD_MUTEX_INITIALIZER;
int reader = 0;

// 读者加锁
void read_lock()
{
    pthread_mutex_lock(&r_count_lock);
    reader++;
    // 如果有人读数据，阻塞写者写数据
    if (reader > 0)
        pthread_mutex_lock(&wlock);
    pthread_mutex_unlock(&r_count_lock);
}

// 读者解锁
void read_unlock()
{
    pthread_mutex_lock(&r_count_lock);
    reader--;
    // 读者为0，释放写锁
    if (reader == 0)
        pthread_mutex_unlock(&wlock);
    pthread_mutex_unlock(&r_count_lock);
}

// 写者加锁
void write_lock()
{
    pthread_mutex_lock(&wlock);
}

// 写者加锁
void write_unlock()
{
    pthread_mutex_unlock(&wlock);
}

int main()
{
    return 0;
}